package com.sneaker.shower.socket;

import com.fasterxml.jackson.annotation.JsonValue;
import com.sneaker.shower.socket.feature.GroupsSignedAble;
import com.sneaker.shower.socket.feature.SignAble;
import com.sneaker.shower.socket.feature.SingelSign;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <h1>ChannelSign</h1>
 * <pre>
 * @Description
 * </pre>
 *
 * @Author lopo
 * @Date 2018/10/19
 */
public class ChannelSign extends GroupsSignedAble implements Serializable {
    private String[] tags;

    public ChannelSign(String... tags) {
        this.tags = tags;
    }

    @Override
    public Collection<SignAble> group() {
        if (tags == null) {
            return Collections.emptyList();
        }
        List<String> body = Arrays.asList(tags);
        List<String> result = new ArrayList<>(add(tags.length));
        result.addAll(body);
        sign(0, 1, body, result);
        return result.stream().map(SingelSign::new).collect(Collectors.toList());
    }

    @JsonValue
    public String[] getTags() {
        return tags;
    }

    public void setTags(String[] tags) {
        this.tags = tags;
    }

    public int add(int a) {
        if (a == 0) {
            return 0;
        }
        return a + add(a - 1);
    }

    public void sign(Integer index, Integer length, List<String> body, List<String> result) {
        if (index + length >= body.size()) {
            return;
        }
        if (body.get(index) == null) {
            return;
        }
        StringBuilder stringBuilder = new StringBuilder(body.get(index));
        for (int i = index + 1; i <= index + length; i++) {
            stringBuilder.append(body.get(i));
            if ((i - index) == length) {
                result.add(stringBuilder.toString());
                sign(index, length + 1, body, result);
            }
        }
        if (length == 1) {
            sign(index + 1, length, body, result);
        }
    }

    @Override
    public void start() {

    }

    @Override
    public void valid() {

    }

    @Override
    public void invalid() {

    }

    @Override
    public void broken() {

    }

    @Override
    public Serializable sign() {
        StringBuilder stringBuilder = new StringBuilder();
        Arrays.stream(tags).forEach((e) -> {
            stringBuilder.append(e);
        });
        return stringBuilder.toString();
    }
}
